package com.winit.project.core.edition;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.util.BAssert;
import com.winit.common.util.ShellRunUtil;
import com.winit.core.server.base.CmdOutputHandler;
import com.winit.core.server.base.ExecResultHandler;
import com.winit.core.server.linux.LinuxLocalServer;
import com.winit.deploy.bean.DeployEnum;
import com.winit.deploy.util.DeployUtil;
import com.winit.project.core.bean.PackageTypeEnum;
import com.winit.project.core.branch.Project;
import com.winit.project.core.set.ProjectSetConfig;
import com.winit.project.util.ProjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * Created by wangjian on 16/9/6.
 */
public class PackageEdition {

    private static final Logger logger = LoggerFactory.getLogger(PackageEdition.class);

    private String path;
    private String editionNum;
    private String projectName;

    private PackageEditionConfig packageEditionConfig;

    public PackageEdition(String projectName, String editionNum, boolean loadInfo) throws Exception {
        BAssert.isEmpty("创建版本PackageEdition,参数存在空值.", logger, projectName, editionNum);
        String projectPath = ProjectUtil.getProjectFilePath(projectName);
        this.path = projectPath + editionNum;
        File file = new File(this.path);
        if (!file.exists()) {
            logger.error("版本目录不存在.path=" + this.path);
            throw new Exception("版本目录不存在.path=" + this.path);
        }
        this.packageEditionConfig = new PackageEditionConfig(projectName, editionNum, loadInfo);
        this.projectName = projectName;
        this.editionNum = editionNum;
    }

    public boolean removeEdition(String qaTestEdition, String buildDir) throws Exception {
        logger.info("删除工程版本.editionNum=" + this.editionNum + ",path=" + this.path);
        if (!StringUtils.isEmpty(qaTestEdition)
                && qaTestEdition.equalsIgnoreCase(this.editionNum)) {
            throw new Exception("该版本为提交测试版本,不能删除.qaTestEdition=" + qaTestEdition + ",path=" + path);
        }

        if (this.editionNum.equals(buildDir)) {
            throw new Exception("工程构建目录,不能删除.path=" + path);
        }

        //测试通过版本不删除
        String testPass = DeployUtil.getProjectVersion(ProjectUtil.getTrunkProjectName(this.projectName), DeployEnum.TESTPASS, "");
        if (testPass.equals(this.projectName + "#" + this.editionNum)) {
            throw new Exception("测试通过版本,不能删除.path=" + path);
        }

        //staging版本不删除
        String staging = DeployUtil.getProjectVersion(ProjectUtil.getTrunkProjectName(this.projectName), DeployEnum.STAGING, "");
        if (staging.equals(this.projectName + "#" + this.editionNum)) {
            throw new Exception("staging版本,不能删除.path=" + path);
        }

        //线上版本不删除
        String online = DeployUtil.getProjectVersion(ProjectUtil.getTrunkProjectName(this.projectName), DeployEnum.ONLINE, "");
        if (online.equals(this.projectName + "#" + this.editionNum)) {
            throw new Exception("线上版本,不能删除.path=" + path);
        }

        String str = ShellRunUtil.runCmds("rm", "-rf", this.path);
        logger.info("删除工程版本.path=" + this.path + ",desc=" + str);
        return StringUtils.isEmpty(str);
    }

    public File getPackage() throws Exception {
        ProjectSetConfig projectSetConfig = new ProjectSetConfig(this.projectName, true);
        String warPath = this.path + "/target/" + this.packageEditionConfig.getNasNum() + "/"
                + projectSetConfig.getWarName() + ".war";
        File file = new File(warPath);
        return file;
    }

    public String getPath() {
        return path;
    }

    public String getEditionNum() {
        return editionNum;
    }

    public PackageEditionConfig getPackageEditionConfig() {
        return packageEditionConfig;
    }

    public JSONObject cpCodeToTrunk(String trunkUrl,String desc){
        JSONObject cmdRt = new JSONObject();
        cmdRt.put("status", true);
        StringBuffer cmd = new StringBuffer();
        cmd.append("source /etc/profile && cd ").append(this.path).append("/temp && rm -rf trunk branch && svn co ").append(trunkUrl)
                .append(" trunk > /dev/null && cd trunk && ls | xargs svn delete > /dev/null && cd ../ && ");
        try {
            Project project = new Project(projectName,true);
            PackageTypeEnum packageType = Enum.valueOf(PackageTypeEnum.class, project.getProjectSetConfig().getPackageType().toUpperCase());
            switch (packageType){
                case MAVEN_WAR:
                case SPRING_BOOT_JAR:
                    cmd.append("tar -zxf code.tgz -C trunk/ && cd trunk && mvn clean -DskipTests > /dev/null");
                    break;
                case PHP:
                    cmd.append("unzip -q -o ../target/").append(project.getProjectSetConfig().getPackageName()).append(".zip -d trunk/ && cd trunk/");
                    break;
                case MAVEN_JAR:
                    cmd.append("cp -R ../../projectCode/* trunk/ && cd trunk && mvn clean -DskipTests > /dev/null");
                    break;
                case ANT_ANDROID:
                default:
                    logger.error("com.winit.project.core.edition.PackageEdition.cpCodeToTrunk 不支持类型.projectName＝" + this.projectName
                            + ",editionNum=" + this.editionNum+",packageType="+packageType.getDesc());
                    cmdRt.put("status", false);
                    cmdRt.put("msg", "不支持的工程类型");
                    return cmdRt;
            }
            String str = ShellRunUtil.runCmds(cmd.toString());
            if(!StringUtils.isEmpty(str)){
                cmdRt.put("status", false);
                cmdRt.put("msg", str);
            }
            if(cmdRt.getBoolean("status")){
                cmd = new StringBuffer();
                cmd.append("source /etc/profile && cd ").append(this.path).append("/temp/trunk && ls | xargs svn add > /dev/null && svn ci -m '").append(desc).append("' > /dev/null && cd ../ && rm -rf trunk branch");
                str = ShellRunUtil.runCmds(cmd.toString());
                if(!StringUtils.isEmpty(str)){
                    cmdRt.put("status", false);
                    cmdRt.put("msg", str);
                }
            }
            if(!cmdRt.getBoolean("status")){
                logger.error("com.winit.project.core.edition.PackageEdition.cpCodeToTrunk 失败.projectName＝" + this.projectName
                        + ",editionNum=" + this.editionNum+",msg="+str);
            }
        }catch (Exception e){
            logger.error("com.winit.project.core.edition.PackageEdition.cpCodeToTrunk 异常.projectName＝" + this.projectName
                    + ",editionNum=" + this.editionNum,e);
            cmdRt.put("status", false);
            cmdRt.put("msg", e.getMessage());
        }
        return cmdRt;
    }
}
